package com.cdh.vod.service;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.cdh.base.DIYException;
import com.cdh.utils.result.ResultCodeEnum;
import com.cdh.vod.utils.AliyunVodSDKUtils;
import com.cdh.vod.utils.VodProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.List;


@Service
@Slf4j
public class VodServiceImpl implements VodService{

    @Autowired
    private VodProperties vod;


    @Override
    public String getPlayAuth(String videoSourceId) throws ClientException {
        DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(
                vod.getKeyid(),
                vod.getKeysecret());
        // 创建请求对象
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        // 设置请求参数
        request.setVideoId(videoSourceId);
        // 发送请求得到响应
        GetVideoPlayAuthResponse response = client.getAcsResponse(request);
        return response.getPlayAuth();
    }

    @Override
        public String uploadVideo(InputStream is, String originalFileName) {
            String title=originalFileName.substring(0,originalFileName.lastIndexOf("."));
            UploadStreamRequest request = new UploadStreamRequest(
                vod.getKeyid(),
                vod.getKeysecret(),
                title,
                originalFileName,
                is);
        //模板组ID（可选）
        // request.setTemplateGroupId(vod.getTemplateGroupId());
        //工作流ID（可选）
        // request.setWorkflowId(vod.getWorkflowId());

        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);

        String videoId = response.getVideoId();
        if (StringUtils.isEmpty(videoId)){
            log.error("阿里云上传失败:"+response.getCode()+"_"+response.getMessage());
            throw new DIYException(ResultCodeEnum.VIDEO_UPLOAD_TOMCAT_ERROR.getCode(),ResultCodeEnum.VIDEO_UPLOAD_TOMCAT_ERROR.getMessage());
        }
        return videoId;
    }

    /**
     * 删除视频
     * @param client 发送请求客户端
     * @return DeleteVideoResponse 删除视频响应数据
     * @throws Exception
     */
    public static DeleteVideoResponse deleteVideo(DefaultAcsClient client) throws Exception {
        DeleteVideoRequest request = new DeleteVideoRequest();
        //支持传入多个视频ID，多个用逗号分隔
        request.setVideoIds("VideoId1,VideoId2");
        return client.getAcsResponse(request);
    }

    @Override
    public void removeVideo(String videoId){
        DefaultAcsClient client = null;
        try {
            client = AliyunVodSDKUtils.initVodClient(
                    vod.getKeyid(), vod.getKeysecret());
            DeleteVideoRequest request = new DeleteVideoRequest();
            //支持传入多个视频ID，多个用逗号分隔
            request.setVideoIds(videoId);
            client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void removeBatchByVideoList(List<String> videoList) {
        DefaultAcsClient client = null;
        try {
            client = AliyunVodSDKUtils.initVodClient(
                    vod.getKeyid(), vod.getKeysecret());
            DeleteVideoRequest request = new DeleteVideoRequest();

            int size = videoList.size();
            StringBuffer idList = new StringBuffer();
            for (int i = 0; i < size; i++) {
                idList.append(videoList.get(i));
                if (i == size -1 || i % 20 == 19){
                    //删除
                    //支持传入多个视频ID，多个用逗号分隔，id不能超过20个
                    log.info(idList.toString());
                    request.setVideoIds(idList.toString());
                    client.getAcsResponse(request);
                    //重置视频列表
                    idList = new StringBuffer();
                }else if (i % 20 < 19){
                    idList.append(",");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
